<?php

/*
采购订单列表
*/
namespace Modules\Intelligent\Http\Repositories;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Modules\Purchasing\Models\Provisional;
use Modules\Purchasing\Models\Provisionalschedule;
use Illuminate\Support\Facades\DB;
use Catch\Exceptions\FailedException;
use Modules\Base\Service\BoxService;
use Modules\Purchasing\Models\Supplier;
use Modules\Purchasing\Models\Supplierschedule;
use Modules\Purchasing\Models\Purchaseorder;
use Modules\Purchasing\Models\Purchaseorderschedule;
use Modules\Warehouse\Models\Storagelocation;
use Modules\Purchasing\Models\Inspectionlist;
use Modules\Purchasing\Models\Inspectionlistcheck;
use extend\services\warehouse\{warehouseService};//引入自定义类
use Modules\Intelligent\Http\Repositories\InspectionlistReget;
use Modules\Intelligent\Models\Otherstorage;
use Modules\Intelligent\Models\Otherstorageschedule;
use Modules\Intelligent\Models\Otheroutboundfrom;
use Modules\Intelligent\Models\OtheroutboundfromSchedule;
use Modules\Intelligent\Models\Lotbinding;
use App\Services\InventoryService;
use App\Enums\InvTransDocType;
use App\Services\KingDeeService;
use Modules\Inventory\Models\Inventory;

class OtheroutboundReget
{
     /*
    数据列表
    */
    public static function list($data = [])
    {
        return self::getBuilder($data)->paginate($data['limit'] ?? 20);
    }


     /**
     *查询列表
     *
     * @param array $data
     * @return Builder
     */
    public static function getBuilder(array $data = []): Builder
    {
       
        $builder = Otheroutboundfrom::query();
        if (isset($data['othernumbers'])) {
            $builder->where('othernumbers', 'like', "%{$data['othernumbers']}%");
        }
        
        if (isset($data['remark'])) {
        $builder->where('remark', 'like', "%{$data['remark']}%");
        }
        
        if (isset($data['incomingtype'])) {
           
                $builder->where('incomingtype',$data['incomingtype']);
           
        }
        if (isset($data['state'])) {
           
                $builder->where('state',$data['state']);
           
        }
        if (isset($data['backstate'])) {
           
                $builder->where('backstate',$data['backstate']);
           
        }
        if (isset($data['deliverydate'])) {
            $builder->where('deliverydate','>=' , $data['deliverydate'][0].' 00:00:00');
            $builder->where('deliverydate','<=' , $data['deliverydate'][1].' 23:59:59');
        }
        if (isset($data['leveltype'])) {
             $builder->where('leveltype',$data['leveltype']);
        }
        
        
        $builder->orderBy('id', 'desc');

        return $builder;
    }

    /*
    数据添加方法
    */
    public static function create(array $data)
    {
        
        $Otheroutboundfrom = new Otheroutboundfrom;
        return self::createOrSave($Otheroutboundfrom, $data);
    }

    //数据添加方法
    public static function createOrSave(Otheroutboundfrom $Otheroutboundfrom,$data)
    {
        // return throw new FailedException('亲！技术还在维修无法出库');
        // exit;
        if(empty($data['detailscheck_all'])){
            return throw new FailedException('亲！数据不能为空');
        }
        
        try {
            //开始起事务
            DB::beginTransaction();

            $Otheroutboundfromdata = [];
            // $Otheroutboundfromdata['othernumbers'] = 'RTCK'.date('Ymd',time()).makeSerial();
            $Otheroutboundfromdata['othernumbers'] = \App\Services\UnitService::createDocno(\App\Enums\OrderNoPrefix::NO_RTCK->value);
            $Otheroutboundfromdata['incomingtype'] = $data['incomingtype'];
            $Otheroutboundfromdata['leveltype'] = $data['leveltype'];
            $Otheroutboundfromdata['deliverydate'] = date('Y-m-d H:i:s',time());
            $Otheroutboundfromdata['remark'] = $data['remark'];
            //新加的
            $Otheroutboundfromdata['fownertypeid'] = $data['cargo_code'];
            $Otheroutboundfromdata['fownerid_number'] = $data['org_code'];
          
            $Otheroutboundfrom->fill($Otheroutboundfromdata);
            $Otheroutboundfrom->save();
            //盘亏出库
            if($data['incomingtype'] == 'QW005'){
                $FDESCRIPTION = $data['incomingtype'];
            }else{
                $FDESCRIPTION = $data['leveltype'];
            }
          

            // $detailscheckOne = [];
            // $detailscheckOne['storagelocation'] = $data['storagelocation'];
            // $detailscheckOne['quantity'] = $data['quantity'];
            // $detailscheckOne['barcode'] = $data['barcode'];
            // $detailscheckOne['otheroutboundfrom_id'] = $Otheroutboundfrom['id'];
            
            $Otheroutboundfrom->detailscheckOne()->createMany( $data['detailscheck_all'] );
            // $Otheroutboundfrom->detailscheckOne()->insert( $detailscheckOne );
            $Model = [];
            //金蝶推送
            foreach($data['detailscheck_all'] as $k=>$v){

                $datares = DB::table('inventory')
                ->select('*')
                ->where('org_code',$data['org_code'])//货主代码
                ->where('org_code',$data['org_code'])//组织代码
                ->where('location',$v['location'])//库位编码
                ->where('material_no',$v['material_no'])//SKU
                ->where('unit',$v['unit'])//单位编码
                ->where('lot_num',$v['barcode'])
                ->first();//批号
               
                if(empty($datares) ){
                    return  throw new FailedException('库存或者信息失败');
                }
    
                $storagelocation = Storagelocation::
                select(
                    'storagelocation.warehousecode',
                    'storagelocation.owning_id',
                    'storagelocation.repositoryname',
                    'storagelocation.person',
                    'stash.fnumber',
                    'stash.fname',
                    'stash.fuseorgid_number',
                    )
                ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
                ->where('storagelocation.warehousecode',$v['location'])
                ->where('storagelocation.id',$v['storagelocation'])
                ->first();
                if(empty($storagelocation) ){
                 return  throw new FailedException('物料数据或者仓库数据出错');
                }
                
                // $Model[$k]['FSRCBILLNO'] = $FBILLNO['warehosnumber'];//原单号采购入库单
                //$Model[$k]['FUNITID'] = $dataPurchaseorderschedule['funitid_number'];//单位（传编码）
                
                $Model[$k]['FSTOCKID'] = $storagelocation['fnumber'];
                $Model[$k]['FQTY'] = $v['quantity'];
                $Model[$k]['FGIVEAWAY'] = 'false';//是否赠品
                $Model[$k]['FSRCSEQ'] = '';//物料源单行号
                $Model[$k]['FMATERIALID'] = $datares->material_no; //SKU（传编码）
                $Model[$k]['FOwnerTypeId'] = 'BD_OwnerOrg';//货主类型
                $Model[$k]['FOwnerId'] = $datares->org_code;//货主编码
                $Model[$k]['FUNITID'] = $datares->unit;//单位
             
                if(!empty($datares)){
                    InventoryService::decInventory(
                        $datares->cargo_code,
                        $Otheroutboundfromdata['othernumbers'],
                        $Otheroutboundfrom['id'],
                        InvTransDocType::OTHER_DELIVERY->value,
                        $datares->material_no,
                        $storagelocation['warehousecode'],
                        $v['barcode'],
                        $v['quantity'],
                        $datares->org_code,
                    );
                }
            }
        
                $order = [
                    'FID'=>0,
                    'FBillNo'=>$Otheroutboundfromdata['othernumbers'],
                    'FDATE'=>date('Y-m-d H:i:s',time()),
                    'FBILLTYPEID'=>"STK_MisDelivery",
                    'FORGID'=>$data['org_code'],//组织
                    'FDESCRIPTION'=>$FDESCRIPTION,
                    // 'FSRCBILLNO'=>'',
                    'FEntity'=>$Model,
                ];
                //金蝶推送
            (new KingDeeService())->form('TVJB_DJWMSDJ')->invokeSave($order);
            
            Otheroutboundfrom::where('id',$Otheroutboundfrom['id'])->update([
                'state'=>1,
                'backstate'=>1,
                'creator_id'=>$data['modifier'],
            ]);
            
            DB::commit();
            return '数据添加成功';
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }

    }

    //修改
    public static function createUpdate($id,$data)
    {
      
        try {
            //开始起事务
            DB::beginTransaction();

            $Inspectionlist = OtheroutboundfromSchedule::query()
            ->where('id',$id)
            ->update(['quantity'=>$data['quantity']]);

            DB::commit();
            return ['code'=>1000,'message'=>'检验成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('服务器飞出地球了请联系技术找回');
        }

    }

    /**
     * 查询一条数据
     *
     */
    public static function find($id)
    {
        return Provisional::query()->with('detailscheckAll')->find($id);
    }

    /**
     * @param $id
     * @return void
     */
    public static function delete($id)
    {
       
        try {
            //开始起事务
            DB::beginTransaction();

            Otheroutboundfrom::query()->where('id',$id)->delete();
            OtheroutboundfromSchedule::query()->where('otheroutboundfrom_id',$id)->delete();
            DB::commit();
            return '删除成功';
        } catch (\Exception $e) {
            DB::rollBack();
           throw new FailedException('服务器飞出地球了请联系技术找回');
        }


    }
     /**修改接口
     * @param $id
     * @return void
     */
    public static function auditupdate($id,$data)
    {
       
        try {
            //开始起事务
            DB::beginTransaction();
            Otherstorageschedule::query()->updateOrCreate(['id' => $id], [
                'quantity' => $data['quantity'],
            ]);
            // $resdata = Provisionalschedule::select('id','provisional_id')->where('provisional_id',$id)->get();
            // foreach($resdata as $k=>$v){
            //     $Inspectionlist = [];
            //     $Inspectionlist['inspectionnumber'] = 'LLJY'.date('Ymd',time()).makeSerial();
            //     $Inspectionlist = Inspectionlist::insertGetId($Inspectionlist);
            //     Otherstorageschedule::query()->updateOrInsert(['id' => $v['id']], [
            //     'inspectionlist_id'=>$Inspectionlist,
            //     ]); 
            //     Provisional::query()->updateOrCreate(['id' => $v['provisional_id']], [
            //         'state' => 1,
            //     ]);   
            // }

            DB::commit();
            return ['code'=>1000,'message'=>'修改成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }

    }


    /**
     * @param $id
     * @return void
     */
    public static function showApi($id)
    {
        
       $data = OtheroutboundfromSchedule::select('id')
        ->where('otheroutboundfrom_id',$id)->first();
        
        $datares = Otheroutboundfrom::select('othernumbers','incomingtype','remark','state','leveltype','backstate')
        ->where('id',$id)->first();
        foreach (Otheroutboundfrom::$Type as $k=>$v){
            $datatype[$v['value']] = $v['label'];
            foreach($v['child'] as $kk=>$vv){
                $child[$vv]=$kk;
                
            }
         }
         $data['incomingtype'] = isset($datatype[$datares['incomingtype']])?$datatype[$datares['incomingtype']]:"";
         $data['leveltype'] = isset($child[$datares['leveltype']])?$child[$datares['leveltype']]:"";
         $data['backstate'] = $datares['backstate']==1?'回写成功':"";
         $data['state'] = $datares['state']==1?'已审核':"";
         $data['othernumbers'] = $datares['othernumbers'];
        if(empty($data)){
            return  throw new FailedException('数据出错');
        }else{
            
            $res = OtheroutboundfromSchedule::select('otheroutboundfrom_id','quantity','storagelocation','barcode','material_no')
            ->where('otheroutboundfrom_id',$id)
            ->get()
            ->toArray();
            foreach($res as $k=>$v){
                
                $storagelocation = Storagelocation::
                select(
                    'storagelocation.warehousecode',
                    'storagelocation.owning_id',
                    'storagelocation.repositoryname',
                    'storagelocation.person',
                    'stash.fnumber',
                    'stash.fname',
                    'stash.fuseorgid_number',
                    )
                ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
                ->where('storagelocation.id',$v['storagelocation'])
                ->first();

                // $storagelocation = DB::table('storagelocation')
                // ->select('warehousecode','owning_id','repositoryname','person')
                // ->where('id',$v['storagelocation'])
                // ->first();

                if(empty($storagelocation)){
                    throw new FailedException('仓库出错');
                }

                $res[$k]['warehousecode'] = $storagelocation->warehousecode;
                $res[$k]['repositoryname'] = $storagelocation->repositoryname;

                $stash = DB::table('stash')
                ->select('fmaterial','fnumber','fname','fuseorgid_number','fuseorgid_name')
                ->where('id',$storagelocation->owning_id)->first();

                $res[$k]['fnumber_stash'] = $stash->fnumber;
                $res[$k]['fname_stash'] = $stash->fname;

                $inventory = DB::table('inventory')
                ->select('location','material_no','unit','qty','lot_num')
                ->where('lot_num',$v['barcode'])
                ->where('material_no',$v['material_no'])
                ->first();

                $material = DB::table('material')
                ->select('fnumber','fname','fspecification','fspecification','funit_name','fuseorgid_name','fbaseproperty_number')
                ->where('fnumber',$v['material_no'])->first();
                $res[$k]['fnumber'] = $inventory->material_no;
                $res[$k]['unit'] = $inventory->unit;
                $res[$k]['fname'] = $material->fname;
                $res[$k]['fspecification'] = $material->fspecification;
                $res[$k]['funit_name'] = $material->funit_name; 
            }
            $data['detailscheck_all'] = $res;
            return ['code'=>1000,'message'=>'扫描成功','data'=>$data];

        }


    }
    /**
     * @param $id
     * @return void
     */
    public static function Barcodename($code)
    {

        $inventory = Inventory::select('org_code','material_no','location','unit','qty','lot_num','cargo_code','id','assign_qty','lock_qty')
        ->where('lot_num',$code)
        ->get()->toArray();
        if(empty($inventory)){
            return throw new FailedException('亲，无法匹配箱号,请重新扫描');
        }
        $data = [];
        
        foreach($inventory as $k=>$v){

            $material = DB::table('material')
            ->select('fname','fnumber','fspecification')
            ->where('fnumber',$v['material_no'])
            ->first();

            $storagelocation = DB::table('storagelocation')
            ->select('warehousecode','owning_id','repositoryname','person','id')
            ->where('warehousecode',$v['location'])
            ->first();  

            $stash = DB::table('stash')
            ->select('fmaterial','fnumber','fname','fuseorgid_number','fuseorgid_name')
            ->where('id',$storagelocation->owning_id)
            ->first();
            $data[$k]['material_no'] = $v['material_no'];
            $data[$k]['material_name'] = $material->fname;
            $data[$k]['location'] = $v['location'];
            $data[$k]['unit'] = $v['unit'];
            $data[$k]['qty'] = $v['qty'] - $v['assign_qty'] - $v['lock_qty'];
            $data[$k]['lot_num'] = $v['lot_num'];
            $data[$k]['fnumber'] = $stash->fnumber;
            $data[$k]['fname'] = $stash->fname;
            $data[$k]['repositoryname'] = $storagelocation->repositoryname;
            $data[$k]['warehousecode'] = $storagelocation->warehousecode;
            $data[$k]['storagelocation'] = $storagelocation->id;
            $data[$k]['cargo_code'] = $v['cargo_code'];
            $data[$k]['org_code'] = $v['org_code'];
            $data[$k]['id'] = $v['id'];
            
        }

        return ['code'=>1000,'message'=>'扫描成功','data'=>$data];

    }

    /**
     * @param $id
     * @return void
     */
    // public static function Barcodename($code)
    // {
            //     $inventory = DB::table('inventory')
            //     ->select('org_code','material_no','location','unit','qty','lot_num')
            //     ->where('lot_num',$code)
            //     ->first();
            //     $material = DB::table('material')
            //     ->select('fname','fnumber','fspecification')
            //     ->where('fnumber',$inventory->material_no)
            //     ->first();

            //     $storagelocation = DB::table('storagelocation')
            //     ->select('warehousecode','owning_id','repositoryname','person')
            //     ->where('warehousecode',$inventory->location)
            //     ->first();  
            //     $stash = DB::table('stash')
            //     ->select('fmaterial','fnumber','fname','fuseorgid_number','fuseorgid_name')
            //     ->where('id',$storagelocation->owning_id)
            //     ->first();
            //     $data = [
            //         'material_no'=>$inventory->material_no,
            //         'material_name'=>$material->fname,
            //         'location'=>$inventory->location,
            //         'unit'=>$inventory->unit,
            //         'qty'=>$inventory->qty,
            //         'lot_num'=>$inventory->lot_num,
            //         'fnumber'=>$stash->fnumber,
            //         'fname'=>$stash->fname,
            //         'repositoryname'=>$storagelocation->repositoryname,
            //         'warehousecode'=>$storagelocation->warehousecode,
            //     ];
            //  return ['code'=>1000,'message'=>'扫描成功','data'=>$data];
    // }
    
    /*审核接口
     * @param $id
     * @return void
     */
    public static function checkPdaApi($id)
    {
       
        $Otherstorage = Otheroutboundfrom::query()
        ->select('id','othernumbers')
        ->where('id',$id)
        ->first()
        ->toArray();
      
        $Otherstorageschedule = OtheroutboundfromSchedule::query()
        ->select('otheroutboundfrom_id','storagelocation','barcode',DB::raw('SUM(quantity) as quantity'),)
        ->where('otheroutboundfrom_id',$id)
        ->groupby(['otheroutboundfrom_id','quantity','storagelocation','barcode'])
        ->get()
        ->toArray();

        if(empty($Otherstorage) || empty($Otherstorageschedule)){
            throw new FailedException('数据出错,无法获取数据');
        }
        
        $Model = [];
        $kingDeeService = new warehouseService();
        $resdata = $kingDeeService->warehousedataApiTwo();
       
        try {
            //开始起事务
            DB::beginTransaction();  

            foreach($Otherstorageschedule as $k=>$v){
                
                // $inventory = DB::table('material')
                // ->select('fnumber','fname','fspecification','funit_number','funit_name','fuseorgid_name','id','fbaseproperty_number','fbaseproperty_name')
                // ->where('id',$v['material_id'])
                // ->first();

                $storagelocation = DB::table('storagelocation')
                ->select('warehousecode','owning_id','repositoryname','person')
                ->where('id',$v['storagelocation'])
                ->first();

                if( empty($inventory) || empty($storagelocation) ){
                    throw new FailedException('物料数据或者仓库数据出错');
                }

                $stash = DB::table('stash')
                ->select('fmaterial','fnumber','fname','fuseorgid_number','fuseorgid_name')
                ->where('id',$storagelocation->owning_id)->first();

              
                if(isset($resdata[$storagelocation->owning_id])){
                    $Model[$k]['FSTOCKID'] = $resdata[$storagelocation->owning_id]['FNumber'];
                }else{
                    return throw new FailedException('库位出错');
                }

                $datares = DB::table('inventory')
                    ->select('*')
                    ->where('org_code',$stash->fuseorgid_number)//使用组织
                    ->where('location',$resdata[$storagelocation->owning_id]['FNumber'])//仓库编码
                    //->where('material_no',$inventory->fnumber)//SKU
                    //->where('unit',$inventory->funit_number)//单位编码
                    ->where('lot_num',$v['barcode'])//批号
                    ->first();

                  // $Model[$k]['FSRCBILLNO'] = $FBILLNO['warehosnumber'];//原单号采购入库单
                $Model[$k]['FSRCSEQ'] = '';//物料源单行号
                $Model[$k]['FMATERIALID'] = $datares->material_no; //SKU（传编码）
                // $Model[$k]['FUNITID'] = $dataPurchaseorderschedule['funitid_number'];//单位（传编码）
                $Model[$k]['FQTY'] = $v['quantity'];
                $Model[$k]['FGIVEAWAY'] = 'false';//是否赠品

                if(!empty($datares)){

                    // $quantity = $datares->qty - $v['quantity'];
                    // $id = DB::table('inventory')->where('id',$datares->id)->update(['qty'=>$quantity]); 
                    //更新库存临时表
                    // $inventory_trans = [
                    //     'org_code'=>$stash->fuseorgid_number,
                    //     'doc_id'=>$id,
                    //     'docno'=>$Otherstorage['othernumbers'],
                    //     'doc_type'=>90,
                    //     'trans_type'=>20,
                    //     'material_no'=>$datares->material_no,//SKU
                    //     'from_location'=>$resdata[$storagelocation->owning_id]['FNumber'],
                    //     'from_lotnum'=>$v['barcode'],
                    //     'from_unit'=>$datares->unit,
                    //     'qty'=>$v['quantity'],
                    //     'to_location'=>$resdata[$storagelocation->owning_id]['FNumber'],
                    //     'to_lotnum'=>$v['barcode'],
                    //     'to_unit'=>$unit->unit,
                    // ];
                    // //变动库存
                    // DB::table('inventory_trans')->insert($inventory_trans);

                    InventoryService::decInventory(
                        $stash->fuseorgid_number,
                        $id,
                        InvTransDocType::OTHER_DELIVERY->value,
                        $datares->material_no,
                        $resdata[$storagelocation->owning_id]['FNumber'],
                        $v['barcode'],
                        $v['quantity']
                    );
                    

                }
            }
            
            $order = [
                'FID'=>0,
                'FBillNo'=>$Otherstorage['othernumbers'],
                'FDATE'=>date('Y-m-d H:i:s',time()),
                'FBILLTYPEID'=>"STK_MISCELLANEOUS",
                'FDESCRIPTION'=>"QW005",//盘盈入库
                'FSRCBILLNO'=>'',
                'FEntity'=>$Model,
            ];
            //金蝶推送
            (new KingDeeService())->form('TVJB_DJWMSDJ')->invokeSave($order);

            return ['code'=>1000,'message'=>'审核成功'];

            DB::commit();
            return '扫描成功';
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('服务器飞出地球了请联系技术找回');
        }
   
    }




}
